//
//  PresentationModalContainer.m
//  CKApp
//
//  Created by CC on 2020/9/6.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "PresentationModalContainer.h"
#import "LcFoundation.h"
#import "PresentationModalController.h"
#import "Masonry.h"
#import "SeparatorCellData.h"

typedef NS_ENUM(NSInteger, ContainerType) {
  CONTENT_TYPE_TABLE,
  CONTENT_TYPE_VIEW,
};

@interface PresentationModalContainer ()
@property(nonatomic, weak) IBOutlet UIView* topContainerView;
@property(nonatomic, weak) IBOutlet UITableView* tableView;
@property(nonatomic, weak) IBOutlet UIView* normalView;
@property(nonatomic, weak) IBOutlet UIView* bottomContainerView;
@property(nonatomic, weak) IBOutlet UIView* separatorLineView;

@property(nonatomic, weak) IBOutlet UILabel* panelTitleLab;
@property(nonatomic, weak) IBOutlet NSLayoutConstraint* titleLeadingCst;

@property(nonatomic, weak) IBOutlet NSLayoutConstraint* bottomContainerViewHeightCst;
@property(nonatomic, weak) IBOutlet UIButton* closeBtn;
@property(nonatomic, weak) IBOutlet NSLayoutConstraint* closeBtnWidth;
@property(nonatomic, weak) IBOutlet NSLayoutConstraint* topContainerHeightConstraint;

@property(nonatomic, weak) PresentationModalController* modalController;

@property(nonatomic, strong) LcCellAdapter* cellAdapter;
@property(nonatomic, strong) NSMutableArray* cellDatas;
@property(nonatomic, copy) NSString* topLeftTitle;
@property(nonatomic, strong) LcFont* topLeftTitleFont;
@property(nonatomic, assign) CGFloat titleLeading;
@property(nonatomic, assign) ContainerType containerType;
@property(nonatomic, strong) UIView* containerView;
@property(nonatomic, assign) CGFloat containerViewHeight;
@property(nonatomic, assign) BOOL isFullScreen;
@property(nonatomic, assign) CGFloat titlePreferredMaxLayoutWidth;

@property(nonatomic, strong) UIView* topView;
@property(nonatomic, assign) CGFloat topViewHeightConstraint;
@property(nonatomic, assign) BOOL isTopViewHidden;
@property(nonatomic, assign) CGFloat manualTopHeight;
@property(nonatomic, assign) CGFloat topViewHeightMin;
@property(nonatomic, assign) BOOL showClearCloseButton;
@property(nonatomic, assign) BOOL showCloseButton;

@property(nonatomic, strong) UIView* bottomView;
@property(nonatomic, assign) CGFloat bottomViewHeightConstraint;

@property(nonatomic, strong) NSIndexPath* scrollToIndexPath;
@property(nonatomic, assign) BOOL scrollWithAnimate;

@property(nonatomic, assign) BOOL isLimitContentHeight;
@property(nonatomic, assign) CGFloat limitContentHeight;

@end

@implementation PresentationModalContainer

- (instancetype)initWithCellDatas:(NSArray*)cellDatas
                     topLeftTitle:(NSString*)topLeftTitle
                     isFullScreen:(BOOL)isFullScreen
               limitContentHeight:(CGFloat)limitContentHeight {
  self = [super init];
  if (self) {
    self.cellDatas = cellDatas.mutableCopy;
    self.topLeftTitle = topLeftTitle;
    self.containerType = CONTENT_TYPE_TABLE;
    self.isFullScreen = isFullScreen;
    self.isLimitContentHeight = limitContentHeight > 0;
    self.limitContentHeight = limitContentHeight;
  }
  return self;
}

- (instancetype)initWithContainerView:(UIView*)containerView
                         topLeftTitle:(NSString*)topLeftTitle
                  containerViewHeight:(CGFloat)containerViewHeight
                   limitContentHeight:(CGFloat)limitContentHeight {
  self = [super init];
  if (self) {
    self.containerView = containerView;
    self.topLeftTitle = topLeftTitle;
    self.containerViewHeight = containerViewHeight;
    self.containerType = CONTENT_TYPE_VIEW;
    self.isFullScreen = containerViewHeight <= 0.0;
    self.isLimitContentHeight = limitContentHeight > 0;
    self.limitContentHeight = limitContentHeight;
  }
  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setUp];
}

- (void)viewDidLayoutSubviews {
  [super viewDidLayoutSubviews];
  if (self.containerType == CONTENT_TYPE_TABLE) {
    [self.tableView setScrollEnabled:floor(self.tableView.contentSize.height) > ceil(self.tableView.bounds.size.height)];
  }
}

- (BOOL)disallowDismissKeyboard {
  return YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  [super scrollViewDidScroll:scrollView];
  [self.view endEditing:YES];
}

- (void)setUp {
  self.titlePreferredMaxLayoutWidth = LcUIUtility.screenWidth - 65.0;
  self.titleLeading = 15.0;
  self.topViewHeightMin = 20.0;
  self.showCloseButton = YES;

  if ([self.fromViewController isKindOfClass:[PresentationModalController class]]) {
    self.modalController = (PresentationModalController*)self.fromViewController;
  }
  self.view.backgroundColor = [UIColor whiteColor];
  if (self.topLeftTitle == nil || self.topLeftTitle.trim.length == 0) {
    self.topLeftTitle = @" ";
  }
  self.topContainerView.backgroundColor = [UIColor whiteColor];
  [self.topContainerView setHidden:self.isTopViewHidden];

  self.closeBtnWidth.constant = self.showCloseButton ? 55.0 : 0.0;

  if (self.topView != nil) {
    [self.panelTitleLab setHidden:YES];
    [self.closeBtn setHidden:YES];
    self.topContainerHeightConstraint.constant = self.topViewHeightConstraint;
    [self.topContainerView addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.edges.equalTo(self.topContainerView);
    }];
  } else {
    self.topViewHeightConstraint = self.topContainerHeightConstraint.constant;
    [self.panelTitleLab setHidden:NO];
    [self.closeBtn setHidden:NO];
    self.panelTitleLab.preferredMaxLayoutWidth = self.titlePreferredMaxLayoutWidth;
    self.panelTitleLab.text = self.topLeftTitle;
    [self.panelTitleLab setLcFont:[LcFont dr17]];
    [self.panelTitleLab setAdjustsFontSizeToFitWidth:YES];
    self.titleLeadingCst.constant = self.titleLeading;
  }

  CGFloat topViewHeight = self.isTopViewHidden ? 20.0 : (self.manualTopHeight > 0 ? self.manualTopHeight : self.topViewHeightConstraint);
  self.topContainerHeightConstraint.constant = topViewHeight;

  if (self.bottomView != nil) {
    [self.bottomContainerView setHidden:NO];
    self.bottomContainerViewHeightCst.constant = self.bottomViewHeightConstraint;
    [self.bottomContainerView addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.edges.equalTo(self.bottomContainerView);
    }];
  }

  CGFloat bottomEdge = [self.modalController bottomEdge];
  CGFloat containerHeight = self.modalController.panelMaxHeight - bottomEdge - LcUIUtility.bottomSafeAreaHeight;

  switch (self.containerType) {
    case CONTENT_TYPE_TABLE: {
      [self.normalView setHidden:YES];
      [self.tableView setHidden:NO];
      [self.tableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
      self.cellAdapter = [[LcCellAdapter alloc] init];
      [self setCellAdapter:self.cellAdapter forTableView:self.tableView];
      [self refreshTableView:NO];
      if (!self.isFullScreen) {
        if (self.isLimitContentHeight) {
          containerHeight = self.limitContentHeight + self.bottomContainerViewHeightCst.constant + topViewHeight;
        } else {
          containerHeight = self.tableView.contentSize.height + self.bottomContainerViewHeightCst.constant + topViewHeight;
        }
      }
      CGFloat maxHeight = LcUIUtility.screenHeight - LcUIUtility.topSafeAreaHeight - LcUIUtility.bottomSafeAreaHeight;
      if ([UIDevice isBangUISize]) {
        maxHeight -= 12.0;
      }
      containerHeight = MIN(containerHeight, maxHeight);
      [self.modalController updatePanelViewHeight:containerHeight isOriginHeight:YES isLimitHeight:self.isLimitContentHeight];
      if (!self.isLimitContentHeight && containerHeight + bottomEdge + LcUIUtility.bottomSafeAreaHeight >= self.modalController.panelMaxHeight) {
        if (self.bottomViewHeightConstraint == 0.0) {
          [self.cellDatas addObject:[SeparatorCellData separatorDataWithHeight:bottomEdge + LcUIUtility.bottomSafeAreaHeight color:[UIColor clearColor] showShadow:NO]];
          [self refreshTableView:NO];
        }
      }
      self.modalController.scrollView = self.tableView;
    }
      break;

    case CONTENT_TYPE_VIEW: {
      [self.normalView setHidden:NO];
      [self.tableView setHidden:YES];
      self.normalView.backgroundColor = [UIColor blueColor];
      [self.normalView addSubview:self.containerView];
      [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.normalView);
      }];
      [self.view layoutIfNeeded];
      if (!self.isFullScreen) {
        if (self.isLimitContentHeight) {
          containerHeight = self.limitContentHeight + self.bottomContainerViewHeightCst.constant + topViewHeight;
        } else {
          containerHeight = self.containerViewHeight + self.bottomContainerViewHeightCst.constant + topViewHeight;
        }
      }
      [self.modalController updatePanelViewHeight:containerHeight isOriginHeight:YES isLimitHeight:self.isLimitContentHeight];
    }

      break;

    default:
      break;
  }

  if (self.modalController.isGaussianBlur) {
//    [self.modalController.panelView gaussianBlur];
    self.view.backgroundColor = [UIColor clearColor];
    self.topContainerView.backgroundColor = [UIColor clearColor];
    self.normalView.backgroundColor = [UIColor clearColor];
    self.panelTitleLab.textColor = [UIColor whiteColor];
  }
}

-(void)refreshTableView:(BOOL)refreshHeight {
  [self.cellAdapter removeAllCellDatas];
  [self.cellAdapter addCellDatas:self.cellDatas];
  [self.cellAdapter refreshAllCells];
  [self.view layoutIfNeeded];
  if (self.scrollToIndexPath != nil) {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
      [self.tableView scrollToRowAtIndexPath:self.scrollToIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:self.scrollWithAnimate];
    } delay:0.25];
    self.scrollToIndexPath = nil;
  }
  if (refreshHeight) {
    CGFloat containerHeight = self.tableView.contentSize.height + self.bottomContainerViewHeightCst.constant + self.topContainerHeightConstraint.constant;
    CGFloat maxHeight = LcUIUtility.screenHeight - LcUIUtility.topSafeAreaHeight - LcUIUtility.bottomSafeAreaHeight;
    if ([UIDevice isBangUISize]) {
      maxHeight -= 12.0;
    }
    containerHeight = MIN(containerHeight, maxHeight);
    [self.modalController updatePanelViewHeight:containerHeight isOriginHeight:YES isLimitHeight:self.isLimitContentHeight];
  }
}

- (void)addTopView:(UIView*)view height:(CGFloat)height {
  LC_CHECK_TRUE(height > 0);
  self.topView = view;
  self.topViewHeightConstraint = height;
}

- (void)addBottomView:(UIView*)view height:(CGFloat)height {
  LC_CHECK_TRUE(height > 0);
  self.bottomView = view;
  self.bottomViewHeightConstraint = height;
}

- (void)reloadTableView:(NSArray*)cellDatas refreshHeight:(BOOL)refreshHeight {
  self.cellDatas = cellDatas.mutableCopy;
  [self refreshTableView:refreshHeight];
}

#pragma mark - Action
- (IBAction)closeClicked:(id)sender {
  [self.modalController presentationModalDismiss:self.modalController.closeHandler];
}

@end
